import QtQuick 2.12

QtObject {
    id: coordinateConverter
    
    // 地球半径（米）
    readonly property real earthRadius: 6378137.0
    
    // 将WGS84经纬度转换为Web墨卡托坐标
    function wgs84ToWebMercator(lon, lat) {
        var x = lon * Math.PI / 180.0 * earthRadius
        var y = Math.log(Math.tan((90.0 + lat) * Math.PI / 360.0)) * earthRadius
        return { x: x, y: y }
    }
    
    // 将Web墨卡托坐标转换为WGS84经纬度
    function webMercatorToWgs84(x, y) {
        var lon = x / earthRadius * 180.0 / Math.PI
        var lat = Math.atan(Math.sinh(y / earthRadius)) * 180.0 / Math.PI
        return { lon: lon, lat: lat }
    }
    
    // 计算两点之间的距离（米）
    function calculateDistance(lon1, lat1, lon2, lat2) {
        var R = earthRadius
        var dLat = (lat2 - lat1) * Math.PI / 180.0
        var dLon = (lon2 - lon1) * Math.PI / 180.0
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(lat1 * Math.PI / 180.0) * Math.cos(lat2 * Math.PI / 180.0) *
                Math.sin(dLon/2) * Math.sin(dLon/2)
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
        return R * c
    }
    
    // 格式化坐标显示
    function formatCoordinate(lon, lat, precision) {
        if (precision === undefined) precision = 6
        return "经度: " + lon.toFixed(precision) + "°, 纬度: " + lat.toFixed(precision) + "°"
    }
    
    // 格式化距离显示
    function formatDistance(distance) {
        if (distance < 1000) {
            return distance.toFixed(1) + " 米"
        } else {
            return (distance / 1000).toFixed(2) + " 公里"
        }
    }
}
